package com.kratos.base.service.account;

import java.io.Serializable;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import com.kratos.base.entity.User;

public class ShiroDbRealm extends AuthorizingRealm{

	protected AccountService accountService;
	
	public void setAccountService(AccountService accountService) {
		this.accountService = accountService;
	}
	
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
		//ShiroUser shiroUser = (ShiroUser) principals.getPrimaryPrincipal();
		//User user = accountService.findUserByLoginName(shiroUser.loginName);
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		//info.addRoles(user.getRoleList());
		return info;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken authcToken) throws AuthenticationException {
		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
//		User user = new User();
//		user.setId(1l);
//		user.setName("admin");
//		user.setLoginName("admin");
//		user.setPassword("123");
//		user.setSalt("123");
//		accountService.registerUser(user);
		User user = accountService.findUserByLoginName(token.getUsername());		
		if (user != null) {
			//byte[] salt = Encodes.decodeHex(user.getSalt());
			SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(new ShiroUser(user.getId(), user.getLoginName(), user.getName()),
					user.getPassword(), ByteSource.Util.bytes(user.getSalt()), getName());
			 return info;
		} else {
			return null;
		}
	}

	/**
	 * 自定义Authentication对象，使得Subject除了携带用户的登录名外还可以携带更多信息.
	 */
	public static class ShiroUser implements Serializable {
		private static final long serialVersionUID = -5042338586051470630L;
		public Long id;
		public String loginName;
		public String name;
		
		public ShiroUser(Long id, String loginName, String name) {
			this.id = id;
			this.loginName = loginName;
			this.name = name;
		}
	}
}
